/**********************************************
 * 
 * File Name				:	CookieUtil.java
 * 
 * Last Changed Date		: 	$Date: 2009-08-01 11:12:53 +0800 (星期六, 01 八月 2009) $
 * 
 * Last Changed Revision	:	$Revision: 86 $
 * 
 * Last Changed Author		:	$Author: cfanboy $
 * 
 * File Header URL			:	$HeadURL: svn://www.svnhost.cn/Busi-Building/code/branch/src/com/busibuilding/utils/CookieUtil.java $
 * 
 * ********************************************
 */

package com.busibuilding.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Class Name: CookieUtil.java 
 * Description: The cookie utils
 * @author: YU Zhipeng
 * @version: 1.0
 * @since: 1.0
 * Date: 2009-07-09
 */
public class CookieUtil {
	
	/**
	 * Get the cookie via the cookie name
	 * @param request
	 * @param name
	 * @return Cookie
	 */
	public static Cookie getCookie(HttpServletRequest request, String name) {
		Cookie cookies[] = request.getCookies();
		if (cookies == null || name == null || name.length() == 0) {
			return null;
		}
		for (int i = 0; i < cookies.length; i++) {
			if (name.equals(cookies[i].getName())) {
				return cookies[i];
			}
		}
		return null;
	}

	/**
	 * Delete the cookie
	 * @param request
	 * @param response
	 * @param cookie
	 */
	public static void deleteCookie(HttpServletRequest request,
			HttpServletResponse response, Cookie cookie) {
		if (cookie != null) {
			cookie.setPath(getPath(request));
			cookie.setValue("");
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
	}

	/**
	 * Set information to cookie
	 * @param request
	 * @param response
	 * @param name Cookie name
	 * @param value The information that want to put into cookie
	 */
	public static void setCookie(HttpServletRequest request,
			HttpServletResponse response, String name, String value) {
		setCookie(request, response, name, value, 0x278d00);
	}

	/**
	 * Set information to cookie
	 * @param request
	 * @param response
	 * @param name Cookie name
	 * @param value The information that want to put into cookie
	 * @param maxAge The max time of this cookie keep alive
	 */
	public static void setCookie(HttpServletRequest request,
			HttpServletResponse response, String name, String value, int maxAge) {
		Cookie cookie = new Cookie(name, value == null ? "" : value);
		cookie.setMaxAge(maxAge);
		cookie.setPath(getPath(request));
		// cookie.setDomain(request.getServerName());
		response.addCookie(cookie);
	}

	/**
	 * Get the cookie stored path.
	 * @param request
	 * @return
	 */
	private static String getPath(HttpServletRequest request) {
		String path = request.getContextPath();
		return (path == null || path.length() == 0) ? "/" : path;
	}

}
